//
//  APIService+Training.m
//  JiZhuiAn
//
//  Created by Easy.Lin on 16/7/6.
//  Copyright © 2016年 Easy. All rights reserved.
//

#import "APIService+Training.h"
#import "TrainingVideoData.h"
#import "TrainingPlanData.h"
#import "TrainingProjectData.h"

@implementation APIService (Training)

- (RACSignal *)getWeekTrainingPlan
{
    @weakify(self);
    return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
        BmobQuery * query = [BmobQuery queryWithClassName:@"Plan"];
        [query whereKey:@"userId" equalTo:self.user.objectId];
        [query findObjectsInBackgroundWithBlock:^(NSArray *array, NSError *error) {
            @strongify(self);
            if (error) {
                [subscriber sendError:error];
            }
            else {
                TrainingPlanData * data = [[TrainingPlanData alloc] initFromBmobObject:[array firstObject]];
                [subscriber sendNext:data];
                [subscriber sendCompleted];
            }
        }];
        return nil;
    }];
}

- (RACSignal *)addNewTrainingPlan
{
    return [self getTrainingProjectWithPartArray:@[@0,@1] severityArray:@[@(self.spineTestData.neckPoint),@(self.spineTestData.waistPoint)]];
}

- (RACSignal *)getTrainingProjectWithPartArray:(NSArray *)partArray severityArray:(NSArray *)severityArray
{
    @weakify(self);
    return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
        BmobQuery * query = [BmobQuery queryWithClassName:@"Training"];
        [query whereKey:@"part" containedIn:partArray];
        [query whereKey:@"severity" containedIn:severityArray];
        [query orderByAscending:@"date"];
        [query findObjectsInBackgroundWithBlock:^(NSArray *array, NSError *error) {
            @strongify(self);
            if (error) {
                [subscriber sendError:error];
            }
            else {
                [[self addNewPlanWithArray:array] subscribeNext:^(NSArray * x) {
                    [subscriber sendNext:x];
                    [subscriber sendCompleted];
                }];
            }
        }];
        return nil;
    }];
}

- (RACSignal *)getTrainingProjectWithPart:(NSInteger)part severity:(NSInteger)severity
{
    return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
        BmobQuery * query = [BmobQuery queryWithClassName:@"Training"];
        [query whereKey:@"part" equalTo:@(part)];
        [query whereKey:@"severity" equalTo:@(severity)];
        [query orderByAscending:@"date"];
        [query findObjectsInBackgroundWithBlock:^(NSArray *array, NSError *error) {
            if (error) {
                [subscriber sendError:error];
            }
            else {
                [subscriber sendNext:array];
                [subscriber sendCompleted];
            }
        }];
        return nil;
    }];
}

- (RACSignal *)addNewPlanWithArray:(NSArray *)traingingArray
{
    return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
        NSMutableArray * planIdArray = [[NSMutableArray alloc] init];
        for (int i = 0; i < traingingArray.count; i ++) {
            if (i % (traingingArray.count/7) == 0 && i != 0) {
                BmobObject * each_1 = [traingingArray objectAtIndex:i-4];
                BmobObject * each_2 = [traingingArray objectAtIndex:i-3];
                BmobObject * each_3 = [traingingArray objectAtIndex:i-2];
                BmobObject * each_4 = [traingingArray objectAtIndex:i-1];
                [planIdArray addObject:@[each_1.objectId,each_2.objectId,each_3.objectId,each_4.objectId]];
            }
            if (i == traingingArray.count-1) {
                BmobObject * each_1 = [traingingArray objectAtIndex:i-3];
                BmobObject * each_2 = [traingingArray objectAtIndex:i-2];
                BmobObject * each_3 = [traingingArray objectAtIndex:i-1];
                BmobObject * each_4 = [traingingArray objectAtIndex:i];
                [planIdArray addObject:@[each_1.objectId,each_2.objectId,each_3.objectId,each_4.objectId]];
            }
        }
        BmobQuery * query = [BmobQuery queryWithClassName:@"Plan"];
        [query whereKey:@"userId" equalTo:self.user.objectId];
        [query findObjectsInBackgroundWithBlock:^(NSArray *array, NSError *error) {
            if (array.count == 0) {
                BmobObject * newObject = [BmobObject objectWithClassName:@"Plan"];
                [newObject setObject:self.user.objectId forKey:@"userId"];
                [newObject setObject:@1 forKey:@"duration"];
                [newObject addObjectsFromArray:planIdArray
                                        forKey:@"trainingIdArray"];
                [newObject saveInBackgroundWithResultBlock:^(BOOL isSuccessful, NSError *error) {
                    if (error) {
                        [subscriber sendError:error];
                    }
                    else {
                        [subscriber sendNext:planIdArray];
                        [subscriber sendCompleted];
                    }
                }];
            }
            else {
                BmobObject * newObject = array.firstObject;
                [newObject addObjectsFromArray:planIdArray
                                        forKey:@"trainingIdArray"];
                [newObject updateInBackgroundWithResultBlock:^(BOOL isSuccessful, NSError *error) {
                    if (error) {
                        [subscriber sendError:error];
                    }
                    else {
                        [subscriber sendNext:planIdArray];
                        [subscriber sendCompleted];
                    }
                }];
            }
        }];
        
        
        return nil;
    }];
}

- (RACSignal *)getTrainingprojectWithId:(NSArray *)idArray
{
    return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
        BmobQuery * query = [BmobQuery queryWithClassName:@"Training"];
        [query whereKey:@"objectId" containedIn:idArray];
        [query orderByAscending:@"time"];
        [query findObjectsInBackgroundWithBlock:^(NSArray *array, NSError *error) {
            if (!error) {
                NSMutableArray * projectArray = [NSMutableArray array];
                for (BmobObject * each in array) {
                    [projectArray addObject:[[TrainingProjectData alloc] initFromBmobObject:each]];
                }
                [subscriber sendNext:projectArray];
                [subscriber sendCompleted];
            }
            else {
                [subscriber sendCompleted];
            }
        }];
        return nil;
    }];
}

- (RACSignal *)getTrainingVideoWithVideoId:(NSArray *)videoIds
{
    return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
        BmobQuery * query = [BmobQuery queryWithClassName:@"videoClip"];
        [query whereKey:@"objectId" containedIn:videoIds];
        [query findObjectsInBackgroundWithBlock:^(NSArray *array, NSError *error) {
            if (!error) {
                NSMutableArray * videoArray = [NSMutableArray array];
                for (BmobObject * each in array) {
                    [videoArray addObject:[[TrainingVideoData alloc] initFromBmobObject:each]];
                }
                NSArray * sortedArray = [videoArray sortedArrayUsingComparator:^NSComparisonResult(TrainingVideoData * obj1, TrainingVideoData * obj2) {
                    if (obj1.sortTag > obj2.sortTag) {
                        return NSOrderedDescending;
                    }
                    return NSOrderedAscending;
                }];
                [subscriber sendNext:sortedArray];
                [subscriber sendCompleted];
            }
            else {
                [subscriber sendCompleted];
            }
        }];
        return nil;
    }];
}

@end
